<template>
  <div class="drawRoute">
    <div class="draw-con">
      <div class="topBar">
          <p-icon @click="toolClck('save')" class="barItem" title="保存" type="save" />
          <p-icon @click="toolClck('delete')" class="barItem" title="删除" type="delete" />
          <p-icon @click="toolClck('redo')" class="barItem" title="重做" type="redo" />
          <p-icon @click="toolClck('undo')" class="barItem" title="撤消" type="undo" />
      </div>
      <div class="mainCon">
        <div class="dLeft">
          <p-collapse v-model="activeKey" :bordered="false">
            <p-collapse-panel key="1" header="基本节点">
              <div
                v-for="(item,index) in baseNode"
                class="baseNode"
                key="1"
                :draggable="item.data"
                :class="{noDrag: item.noDrag}" 
                @dragstart="onDrag($event, item)"
              >
              {{item.name}}
             <!--  <div
                class="baseNode"
                key="2"
                :draggable="endNode.data"
                :class="{noDrag: endNodeNoDrag}" 
                @dragstart="onDrag($event, endNode)"
              > -->
              </div>
            </p-collapse-panel>
            <p-collapse-panel key="3" header="工序节点">
              <p-input-search
                  class="inputSearch"
                  placeholder="请输入编码/名称"
                  v-model="leftTreeKeyWord"
                  @search="inputSearchChange"
                />
                <div class="processItemWrap">
                  <div :draggable="processNode.data"
                        @dragstart="onDrag($event, processNode, item)" 
                        class="processNode"
                        :key="index"
                        :title="`${item.processmcode}(${item.processmname})`"
                        :class="{noDrag: item.noDrag}" 
                        v-for="(item,index) in processData">
                    {{`${item.processmcode}(${item.processmname})`}}
                  </div>
                  <NoData v-show="processData.length === 0"/>
                </div>
            </p-collapse-panel>
          </p-collapse>
        </div>
        <div class="dMid">
          <div class="canvas" id="topology-canvas"></div>

        </div>
        <div class="dRight">
          <div v-show="selectNodeCheck">
            <p-tree v-if="curNode.data.configTree.length > 0 && treeTag"
              :replaceFields="replaceFields"
              :tree-data="curNode.data.configTree"
              :selectedKeys.sync="selectedKeys"
              @select="treeSelect"
              showLine
              selectable
              defaultExpandAll
            />
            <NoData v-show="curNode.data.configTree.length === 0"/>
          </div>
          <div v-show="!selectNodeCheck" class="rightBarNoSelect">
            <div class="tipsTitle">快捷键小提示</div>
            <div> 全选: <span>Ctrl+A</span></div>
            <div> 删除: <span>Delete</span></div>
            <div> 移动5像素: <span>方向键</span></div>
            <div> 移动1像素: <span>Ctrl + 方向键</span></div>
          </div>
        </div>
      </div>
    </div>
    <div class="proceessAtrrPanel" v-show="tabsShow && selectNodeCheck && curNode.data.configTree.length">
      <p-tabs :animated="false" v-model="tabActiveKey" @change="tabsChange">
        <p-tab-pane
          v-for="item in tabsData"
          :key="item.key" 
          :tab="item.label">
        </p-tab-pane>
      </p-tabs>
      <div class="componentRender">
        <keep-alive>
          <component ref="componentRender" :is="componentId" :options="options" :site-index="siteIndex"></component>
        </keep-alive>
      </div>
    </div>
    <div id="dynDiv" v-show="false"></div>
    <p-modal 
      okText="确定" 
      cancelText="取消" 
      v-model="processModal" 
      :title="firstTitle" 
      @cancel="handleCancel" 
      @ok="handleOk">
      <p-table
        v-if="tableTag"
        rowKey="id"
        :scroll="{y:500}"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :rowClassName="rowClassName"
        :pagination="false"
        :defaultExpandAllRows="true"
        :columns="columns"
        :data-source="modalTableData">
        <template slot="operation" slot-scope="text, record">
          <span v-if="record.processlayer === 3 && record.childrenLength > 1 && record.index > 0" title="上移" class="operateBtn" @click="moveUp(text, record)">
            <p-icon type="arrow-up" />
          </span>
          <span v-if="record.processlayer === 3 && record.childrenLength > 1 && record.index !== record.childrenLength - 1" title="下移" class="operateBtn" @click="moveDown(text, record)">
            <p-icon type="arrow-down" />
          </span>
        </template>
      </p-table>
      <div class="tbExra">
        <span>二级工序关系<span class="tClass">*并行</span></span>
        <span>工站关系<span class="tClass">*串行</span></span>
      </div>
    </p-modal>
  </div>
</template>
 
<script>
import siteAttr from "./siteAttr";
import skill from "./siteSkill";
import siteSource from "./siteSource";
import processbom from "./siteBom";
import sop from "../components/sopMake/index.vue";
import wirerod from "./siteLineList";
import module from "./siteComponentList";
import consume from "./siteLossArg";
import gram from "./siteProgram";
import NoData from "@/components/NoData";
import mesPeProcess from "@/api/mesPeProcess";
import { Topology } from '@topology/core';
import _ from "lodash";
// import { register as registerFlow } from '@topology/flow-diagram';
const baseNode = [
  {
    "name": "开始",
    "data": {
      "text": "开始",
      "rect": {
        "width": 50,
        "height": 50
      },
      data: {
        nodeType: 'baseNode',
        key: 'start',
      },
      "borderRadius": 0.5,
      "name": "rectangle",
    }
  },
  {
    "name": "结束",
    "data": {
      "text": "结束",
      "rect": {
        "width": 50,
        "height": 50
      },
      data: {
        nodeType: 'baseNode',
        key: 'end',
      },
      "borderRadius": 0.5,
      "name": "rectangle"
    }
  }
];
export default {
  name: "drawRoute",
  props: {
    pdata: Object, 
  },
  components: {
    NoData,
    siteAttr,
    skill,
    siteSource,
    processbom,
    sop,
    wirerod,
    module,
    consume,
    gram,
  },
  data() {
    return {
      firstTitle: '',
      option: {},
      siteIndex: {},
      tabActiveKey: 'siteAttr',
      componentId: 'siteAttr',
      tableTag: true,
      treeTag: true,
      tabsShow: false,
      selectNodeCheck: false,
      modalTableData: [],
      curSelectedNodes: null,
      selectedRowKeys: [],
      processDataCopy: [],
      selectedKeys: [],
      processModal: false,
      curNode: {
        data:{
          configTree: [],
        }
      },
      replaceFields: {
        children:'children', 
        title:'showName', 
        key:'id' 
      },
      allAabsData: [
        {
          label: '技能',
          key: 'skill',
        },
        {
          label: '资源',
          key: 'siteSource',
        },
        {
          label: '工序BOM',
          key: 'processbom',
        },
        {
          label: 'SOP',
          key: 'sop',
        },
        {
          label: '线材清单',
          key: 'wirerod',
        },
        {
          label: '组件清单',
          key: 'module',
        },
        {
          label: '耗损系数',
          key: 'consume',
        },
        {
          label: '程序',
          key: 'gram',
        },
      ],
      commmonTabsData: [
        {
          label: '工站基本属性',
          key: 'siteAttr',
        },
      ],
      tabsData: [
        {
          label: '工站基本属性',
          key: 'siteAttr',
        },
      ],
      baseNode,
      processNode: {
        "name": "",
        "data": {
          text: '',
          rect: {
            width: 140,
            height: 50
          },
          image: require("@/assets/images/setting.png"),
          imageWidth: 30,
          imageHeight: 30,
          borderRadius: 0.3,
          elementId: '',
          name: 'rectangle',
          is3D: true,
          data: {
            key: 'process',
            secondTree: [], // 二级工序及工站
            firstItem: {}, // 一级工序数据
            selectedRowKeys: [], // 配置工序弹框中已勾选的[id]
            selectedKeys: [], // 已配置的工序及工站节点 选中的的工站[id]
            configTree: [], // 已配置的工序及工站节点
          },
        }
      },
      columns: [
        {
          title: '二级工序/工站编码',
          dataIndex: 'processmcode',
          ellipsis: true,
        },
        {
          title: '二级工序/工站名称',
          dataIndex: 'processmname',
          ellipsis: true,
        },
        {
          title: '调整',
          dataIndex: 'operate',
          align: 'right',
          width: 100,
          scopedSlots: { customRender: 'operation' },
        },
      ],
      activeKey: ['1','3'],
      leftTreeKeyWord: '',
      expandedKeys: [],
      autoExpandParent: true,
      nodeConfigTreeData: [],
      allTreeData: [],
      processData: [],
      canvas: null,
    };
  },
  computed: {
    baseInfo(){
      return this.$parent.$refs.BaseInfo.form
    },
    handle(){
      return this.$route.query.handle
    }
  },
  created() {
    this.getAllFirstDef();
    this.getProcesstree();
  },
  mounted(){
    const that = this;
    this.canvas = new Topology('topology-canvas', {
      on: this.onMessage,
      hideInput: true,
      hideSizeCP: true,
      hideRotateCP: true,
    });
    let pens = [];
    if ( this.handle === 'edit' || this.handle === 'addAndEdit' ){
      pens = JSON.parse(this.pdata.frontData);
      // 复制新增 清空工站bom数据
      if ( this.handle === 'addAndEdit' ){
        pens.forEach( element =>{
          if (element.data && element.data.key === "process" && element.data.configTree.length > 0){
            element.data.configTree.forEach( ele =>{
              ele.children.forEach( el =>{
                if (el.bomData.length > 0){
                  el.bomData = [];
                }
              });
            });
          }
        });
      }
    }
    const json = {
      pens,
      grid: true,
    };
    this.canvas.open(json);
    if ( this.handle === 'edit' || this.handle === 'addAndEdit' ){
      this.canvas.data.pens.forEach(el =>{
        if (el.data && el.data.key === 'process'){
          this.createDiv({
            processmname: el.text,
          },el.elementId);
          el.init();
          this.canvas.render();
        }
      });
    }
    document.addEventListener("click",function(e){
      if (e.target.className === 'elementClassChild'){
        const attributes = e.target.attributes;
        that.processModal = true;
        
        if ( that.curNode.data ){
          that.tableTag = false;
          that.treeTag = false;
          that.firstTitle = that.curNode.data.firstItem.processmname;
          that.modalTableData = that.handleProcessTree(that.curNode.data.secondTree || []);
          // 为了让每次的表格，树都展开
          that.$nextTick( el => {
            that.tableTag = true;
            that.treeTag = true;
          })
          that.selectedRowKeys = that.curNode.data.selectedRowKeys;
        } 
      }
      if (e.target.className === 'elementClass'){
        that.treeTag = false;
        that.$nextTick( el => {
          that.treeTag = true;
        })
      }
    });
  },
  methods: {
    moveUp(text, {index,pIndex}){
      // 缓存元素
      const temp = this.modalTableData[pIndex].children[index];
      // 当前元素
      this.modalTableData[pIndex].children[index] = this.modalTableData[pIndex].children[index - 1];
      this.modalTableData[pIndex].children[index].index += 1;
       // 上一个元素
      this.modalTableData[pIndex].children[index - 1] = temp;
      this.modalTableData[pIndex].children[index - 1].index -= 1;
      this.modalTableData.splice();
    },
    moveDown(text, {index,pIndex}){
      // 缓存元素
      const temp = this.modalTableData[pIndex].children[index];
      // 当前元素
      this.modalTableData[pIndex].children[index] = this.modalTableData[pIndex].children[index + 1];
      this.modalTableData[pIndex].children[index].index -= 1;
      // 下一个元素
      this.modalTableData[pIndex].children[index + 1] = temp;
      this.modalTableData[pIndex].children[index + 1].index += 1;
      this.modalTableData.splice(); 
    },
    // 根据id找到curSelectedNodes
    findAndSetCurSelectedNodes(id,configTree){
      let item = {};
      configTree.forEach( el =>{
        el.children.forEach( e =>{
          if ( id === e.id ){
            item = e;
          }
        });
      });
      if ( !this.curSelectedNodes ){
        this.curSelectedNodes = item;
      }
    },
    // 获取画布中正确的流向的节点
    getSortNodeArr(){
      let pens = this.canvas.data.pens;
      // 开始节点
      let startNode = pens.find( el => el.data.key === 'start' );
      if ( !startNode ) {
        this.$message.error("缺少开始节点")
        return;
      }
      // 结束节点
      let endNode = pens.find( el => el.data.key === 'end' );
      if ( !endNode ) {
        this.$message.error("缺少结束节点")
        return;
      }
      // 已知id, 
      // 获取 连线 的 to id
      // 已知id 
      // 获取 连线 的 to id
      // 直到 当前id对应的节点 为结束节点为止
      let resArr = [];
      const getNextNode = (argNode) => {
        // 获取连接这个节点的线段
        let lineNode = pens.find( el => el.from && (el.from.id === argNode.id) );
        if ( !lineNode ){
          this.$message.error(`${argNode.text} 节点未连接其他节点`);
          resArr = [];
        }else {
          let curNode = pens.find( el => el.id === lineNode.to.id );
          // 如果线的两端不是开始结束节点 todo 
          // 不到结束节点继续，到结束节点 就结束了
          if ( curNode && curNode.data.key !== 'end' ){
            resArr.push(curNode);
            getNextNode(curNode)
          }
        }
      }
      getNextNode(startNode);
      return resArr;
    },
    tabsChange(key) {
      this.componentId = key;
      this.setSitePanelData();
    },
    // 获取工时调整的的数据 
    getWorkingHour(){
      let backArr = [];
      let secondTree = [];
      let siteNodeArr = _.cloneDeep(this.canvas.data.pens);
      siteNodeArr = siteNodeArr.filter( el => el.data && el.data.key === 'process' );
      siteNodeArr.forEach( el =>{
        el.data.configTree.forEach( e =>{
          e.hour = 0;
          e.disabled = false;
          e.scopedSlots = { title: 'title' }; // 给工时调整用
          e.children.forEach( es =>{
            es.hour = es.siteAttr.workstationHour || 0; // 一级工序工时
            e.hour += es.hour;  // 二级工序工时
            es.scopedSlots = { title: 'title' }; // 给工时调整用
          });
        })
        secondTree = secondTree.concat(el.data.configTree);
      });
      this.allTreeData.forEach( (el, index) =>{
        let item = _.cloneDeep(el);
        item.topHour = 0;
        item.children = [];
        secondTree.forEach( e =>{
          if ( el.id === e.pid ){
            item.children.push(e);
          }
        });
        backArr[index] = item
        backArr[index].children = item.children;
      });
      backArr = backArr.filter( el => el.children.length > 0 );
      backArr.forEach( el =>{
        el.hour = 0;
        const hourArr = el.children.map( et => et.hour);
        if( hourArr.length > 0 ){
          el.hour = hourArr.reduce((total, num) => (total + num));
        }
        el.scopedSlots = { title: 'title' }; // 给工时调整用
      });
      console.log(backArr)
      return backArr;
    },
    // 获取物料分配数据
    getMaterial(){
      let siteNodeArr = _.cloneDeep(this.canvas.data.pens);
      siteNodeArr = siteNodeArr.filter( el => el.data && el.data.key === 'process' );
      let processbomAll = [];
      siteNodeArr.forEach( el =>{
        el.data.configTree.forEach( e =>{
          e.children.forEach( es =>{
            const workstationName = es.siteAttr.workstationName;
            const workstationCode = es.siteAttr.workstationCode;
            if ( es.bomData.length > 0 ){
              // 添加所属工站信息
              es.bomData.forEach( d => {
                d.workstationName = workstationName;
                d.workstationCode = workstationCode;
              });
              processbomAll = processbomAll.concat(es.bomData);
            }
          })
        });
      });
      let pIndex = 0;
      // 按物料编码划分
      let processbomAllMap = {};
      processbomAll.forEach( el =>{
        if (processbomAllMap[el.mcode]){
          // 添加这个主物料下的分配的工站物料 总数量，可分配数量置空
          el.remainQuantitySelf = null;
          el.allQuantitySelf = null;
          el.parent = processbomAllMap[el.mcode][0];
          processbomAllMap[el.mcode].push(el);
        }else {
          // 添加一个主物料
          let curItem = _.cloneDeep(el);
          // 主物料没有工站所需数量，工站名称以及编码 置空
          curItem.stationsRequired = null;
          curItem.workstationName = null;
          curItem.workstationCode = null;
          curItem.maintenanceKey = 2; // 主物料默认不是关键物料
          curItem.remainQuantitySelf = curItem.remainQuantity;
          curItem.allQuantitySelf = curItem.allQuantity;
          curItem.index = pIndex;
          processbomAllMap[el.mcode] = [];
          processbomAllMap[el.mcode].push(curItem);

          // 添加这个主物料下的分配的工站 总数量，可分配数量置空
          el.remainQuantitySelf = null;
          el.allQuantitySelf = null;
          el.parent = processbomAllMap[el.mcode][0];
          processbomAllMap[el.mcode].push(el);
          pIndex++;
        }
      })
      
      let processbomArr = [];
      for(const key in processbomAllMap ){
        processbomArr.push(...processbomAllMap[key]);
      }
      console.log(processbomArr);
      return processbomArr;
    },
    // 设置工站面板的数据
    setSitePanelData(){
      console.log(this.componentId);
      const { pIndex, index } = this.siteIndex;
      const curNode = this.curNode.data.configTree[pIndex].children[index];
      console.log(curNode)
      switch ( this.componentId ){
        // 工站基本属性
        case 'siteAttr':
          this.options = curNode.siteAttr;
          break;
        // 工站技能
        case 'skill':
          this.options = curNode.skillData;
          break;
        // 工站资源
        case 'siteSource':
          this.options = curNode.sourceData;
          break;
        // 工站BOM
        case 'processbom':
          this.options = curNode.bomData;
          break;
        // 线材清单
        case 'wirerod':
          this.options = curNode.wirerodData;
          break;
        // 组件清单
        case 'module':
          this.options = curNode.moduleData;
          break;
        // 耗损系数
        case 'consume':
          this.options = curNode.consumeData;
          break;
        // 程序
        case 'gram':
          this.options = curNode.gramData;
          break;
        // sop
        case 'sop': 
          curNode.sopData.bomData = curNode.bomData;
          curNode.sopData.sourceData = curNode.sourceData;
          curNode.sopData.gramData = curNode.gramData;
          curNode.sopData.siteAttr = curNode.siteAttr;
          this.options = curNode.sopData;
          break;
      }
    },
    treeSelect(selectedKeys, {selectedNodes}){
      let pIndex = 0;
      let index = 0;
      if ( selectedNodes.length > 0 ){
        this.curNode.data.configTree.forEach( (el, elIndex) =>{
          el.children.forEach( (e, i) =>{
            if (selectedKeys[0] === e.id){
              pIndex = elIndex;
              index = i;
            }
          });
        });
        this.siteIndex = { index, pIndex,};
        this.curSelectedNodes = selectedNodes[0].data.props;
        this.curNode.data.selectedKeys = selectedKeys;
        this.setSitePanelData();
        const processmcode = this.curSelectedNodes.processmcode;
        this.queryByDefinitionCode(processmcode);
        this.tabsShow = true;
      }else {
        this.tabsShow = false;
        this.curNode.data.selectedKeys = [];
        this.curSelectedNodes = {};
      }
    },
    // 获取所有节点的工序树，给工时调整用
    getNodeProcessData(){

    },
    // 获取工站有哪些页签
    queryByDefinitionCode(code){
      mesPeProcess.queryByDefinitionCode({
        code
      }).then( (res) =>{
        if ( res.code === 0 ){
          let tabsArr = [];
          const curData = res.data;
          // 1 显示 2隐藏
          const defaultVal = 1;
          const defineObj =  {
              siteSource: curData.siteSource || defaultVal,  // 默认隐藏
              skill: curData.skill || defaultVal,  // 默认隐藏
              processbom: curData.processbom || defaultVal,  // 默认隐藏
              sop: curData.sop || defaultVal,  // 默认隐藏
              wirerod: curData.wirerod || defaultVal,  // 默认隐藏
              module: curData.module || defaultVal,  // 默认隐藏
              consume: curData.consume || defaultVal,  // 默认隐藏
              gram: curData.gram || defaultVal,  // 默认隐藏
          };
          this.allAabsData.forEach( el =>{
            if( defineObj[el.key] === 1 ){
              tabsArr.push(el);
            }
          });
          tabsArr = [...this.commmonTabsData, ...tabsArr];
          this.tabsData = _.cloneDeep(tabsArr);
          /* this.componentId = 'siteAttr';
          this.tabActiveKey = 'siteAttr'; */
        }
      })
    },
    handleOk(){
      this.processModal = false;
      this.curNode.data.selectedRowKeys =  this.selectedRowKeys;
      this.curNode.data.configTree = this.getSelectTree();
    },
    inputSearchChange(){
      this.processData = this.processDataCopy.filter( el =>{
        return el.processmname.includes(this.leftTreeKeyWord) || el.processmcode.includes(this.leftTreeKeyWord) 
      })
    },
    createStationData(curEl, pEl){
      // 工站的基本信息
      if ( !curEl.siteAttr ){ 
        let topProcessName = this.processData.filter( cl => cl.id === pEl.pid );
        topProcessName = topProcessName[0].processmname;
        curEl.siteAttr = {
          workstationName: curEl.processmname,
          topProcessName,
          collectionType: '',
          workstationCode: curEl.processmcode,
          workstationHour: 0,
          returnWorkstationCode: '',
          twoProcessName: pEl.processmname,
          twoProcessCode: pEl.processmcode,
          collectionBarcode: '',
          workAddressCode: '',
        }
      }
      // 工站技能
      if(!curEl.skillData){
        curEl.skillData = [];
      }
      // 工站资源
      if(!curEl.sourceData){
        curEl.sourceData = [];
      }
      // 工站BOM
      if(!curEl.bomData){
        curEl.bomData = [];
      }
      // 线材清单
      if(!curEl.wirerodData){
        curEl.wirerodData = [];
      }
      // 组件清单
      if(!curEl.moduleData){
        curEl.moduleData = [];
      }
      // 耗损系数
      if(!curEl.consumeData){
        curEl.consumeData = [];
      }
      // 程序
      if(!curEl.gramData){
        curEl.gramData = [];
      }
      // sop
      if(!curEl.sopData){
        curEl.sopData = {
          bomData: [],  // 工序bom
          sourceData: [], // 工装清单
          gramData: [], // 程序
          picturesData: [], // 图片
          stepData: [], // 操作步骤
        };
      }
      // 选中的工站[id]
      curEl.selectedKeys = [];
    },
    getSelectTree(){
      const curTree = [];
      console.log(this.selectedRowKeys)
      const checkId = id => this.selectedRowKeys.includes(id)
      let curTableData = _.cloneDeep(this.modalTableData);
      curTableData.forEach( el => {
        if ( checkId(el.id) ){
          // 二级工序节点不可点击 只有工站才可以
          el.disabled = true;
          el.children = el.children.filter(e => checkId(e.id));
          curTree.push(el);
        }
      });
      
      curTree.forEach((element, index) =>{
        this.curNode.data.configTree.forEach( (configTreeEl, ind) =>{
          if (element.id === configTreeEl.id){
            element.children.forEach( (elementChildEl,elementChildElIndex) =>{
              configTreeEl.children.forEach( configTreeElChildEl =>{
                if( elementChildEl.id === configTreeElChildEl.id ){
                  element.children[elementChildElIndex] = configTreeElChildEl; 
                }
              });
            });
          }
        })
      });
      curTree.forEach( ele =>{
        ele.children.forEach( el =>{
          this.createStationData(el,ele);
        });
      });
      console.log(curTree);
      return curTree;
      /* curTree.forEach( (el, index) => {
        let curArr = [];
        const curNode = this.curNode.data.configTree;
        const curFindData = curNode.find( cEl => cEl.id === el.id );
        // 新增
        if ( curFindData === undefined ){
          el.children.forEach( e => {
            if ( checkId(e.id) ){
              if (!el.children){
                el.children = []
              }
              // 工站的基本信息
              if ( !e.siteAttr ){ 
                let topProcessName = this.processData.filter( cl => cl.id === el.pid );
                topProcessName = topProcessName[0].processmname;
                e.siteAttr = {
                  workstationName: e.processmname,
                  topProcessName,
                  collectionType: '',
                  workstationCode: e.processmcode,
                  workstationHour: 0,
                  returnWorkstationCode: '',
                  twoProcessName: el.processmname,
                  twoProcessCode: el.processmcode,
                  collectionBarcode: '',
                  workAddressCode: '',
                }
              }
              // 工站技能
              if(!e.skillData){
                e.skillData = [];
              }
              // 工站资源
              if(!e.sourceData){
                e.sourceData = [];
              }
              // 工站BOM
              if(!e.bomData){
                e.bomData = [];
              }
              // 线材清单
              if(!e.wirerodData){
                e.wirerodData = [];
              }
              // 组件清单
              if(!e.moduleData){
                e.moduleData = [];
              }
              // 耗损系数
              if(!e.consumeData){
                e.consumeData = [];
              }
              // 程序
              if(!e.gramData){
                e.gramData = [];
              }
              // sop
              if(!e.sopData){
                e.sopData = {
                  bomData: [],  // 工序bom
                  sourceData: [], // 工装清单
                  gramData: [], // 程序
                  picturesData: [], // 图片
                  stepData: [], // 操作步骤
                };
              }
              // 选中的工站[id]
              e.selectedKeys = [];
              curArr.push(e);
            }
          });
        // 以前就有
        }else {
          curArr = curFindData.children;
        }
        el.children = curArr;
      }); */
    },
    handleCancel(){
      this.selectedRowKeys = this.curNode.data.selectedRowKeys;
    },
    toolClck(handle){
      if ( handle === 'delete' ){
        this.canvas.delete();
      }else if( handle === 'redo' ){
        this.canvas.redo();
      }else if( handle === 'undo' ){
        this.canvas.undo();
      }else if( handle === 'save' ){
        console.log(this.canvas.data.pens);
        this.getMaterial();
      }
    },
    rowClassName(record, index) {
      return `processlayer${record.processlayer}`
    },
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys);
      // 变化的keys 差集
      let changeKeys = _.xor(selectedRowKeys, this.selectedRowKeys);
      // 只针对改变一项时，全选/取消 不用管
      const curcLength = this.selectedRowKeys.length;
      const cLength = selectedRowKeys.length;
      if ( changeKeys.length === 1 && cLength > 0){
        let item  = this.modalTableData.filter( el => el.id === changeKeys[0]);
        // 选中
        if ( curcLength <  cLength){
          // 选中父级节点
          if (item.length === 1){
           const children =  item[0].children || [];
           const curChildrenId = children.map( el => el.id);
           this.selectedRowKeys = _.union(selectedRowKeys, curChildrenId);
          // 选中子级节点 如果父节点未被选上 需要勾选
          }else {
            let choosrItem = {};
            let choosrIParentTtem = {};
            this.modalTableData.forEach( el =>{
              el.children.forEach( e =>{
                if ( changeKeys[0] === e.id ){
                  choosrItem = e;
                  choosrIParentTtem = el;
                }
              });
            });
            this.selectedRowKeys = _.union(selectedRowKeys, [choosrIParentTtem.id]);
          }
        // 取消选中
        }else {
          // 取消选中父级节点, 子节点全都去掉勾选
          if (item.length === 1){
           const children =  item[0].children || [];
           const curChildrenId = children.map( el => el.id);
           this.selectedRowKeys = selectedRowKeys.filter( el => !curChildrenId.includes(el));
          // 取消选中子级节点 如果子级节点都取消了，父节点也取消
          }else {
            let unChoosrItem = {};
            let unChoosrIParentTtem = {};
            this.modalTableData.forEach( el =>{
              el.children.forEach( e =>{
                if ( changeKeys[0] === e.id ){
                  unChoosrItem = e;
                  unChoosrIParentTtem = el;
                }
              });
            });
            const parentIds = unChoosrIParentTtem.children.map( el => el.id );
            const check1 = selectedRowKeys.filter(el => parentIds.includes(el));
            if ( check1.length === 0 ){
              this.selectedRowKeys = selectedRowKeys.filter( el => el !== unChoosrIParentTtem.id );
            }else {
              this.selectedRowKeys = selectedRowKeys;
            }
          }
        }
      }else {
        this.selectedRowKeys = selectedRowKeys;
      }
    },
    createDiv(item,elementId){
      // 创建dom
      const curId = elementId || `elementId${new Date().getTime()}`;
      
      const div1 = document.createElement("div");
      div1.setAttribute('id',curId);
      div1.setAttribute('class',`elementClass`);
      div1.setAttribute('title', item.processmname);

      const div2 = document.createElement("div");
      div2.setAttribute('class',`elementClassChild`);
      div2.setAttribute('title', item.processmname);
      /* div2.setAttribute('data-code', item.processmcode);
      div2.setAttribute('data-id', item.id); */

      div1.appendChild(div2);
      document.getElementById('dynDiv').appendChild(div1);
      return curId;
    },
    onDrag(event, node, item) {
      if (node.data.data.key === 'process'){
        node.data.text = item.processmname;
        node.data.data.firstItem = item;
        node.data.elementId = this.createDiv(item);
        // 一级工序下的的二级工序以及工站
        let secondTree = this.allTreeData.filter( el => el.id === item.id);
        if (secondTree[0] && secondTree[0].children){
          secondTree = secondTree[0].children;
        }
        node.data.data.secondTree = _.cloneDeep(secondTree);
      }
      event.dataTransfer.setData('Text', JSON.stringify(node.data));
    },
    checkTreeSelect(){
      if ( this.selectedKeys.length > 0 ){
        let item = {};
        let pIndex = 0;
        let index = 0;
        this.curNode.data.configTree.forEach( (el, elIndex) =>{
          el.children.forEach( (e, i) =>{
            if ( e.id === this.selectedKeys[0] ){
              item = e;
              pIndex = elIndex;
              index = i;
            }
          })
        })
        if ( item.processmcode ){
          this.siteIndex = { index, pIndex,};
          this.setSitePanelData();
          this.queryByDefinitionCode(item.processmcode);
        }
        this.tabsShow = true;
      }else {
        this.tabsShow = false;
      }
    },
    checkDrag(node){
      const toFalse = () => {
        if ( this.processData && this.processData.length > 0 ){
          this.processData.forEach( e => {
            e.noDrag = false;
          });
          this.processData.splice();
        }
      }
      const toBaseNodeFalse = () => {
        this.baseNode.forEach( e => {
          e.noDrag = false;
        });
      }
      if ( this.canvas && this.canvas.data ){
        // 基本节点
        const baseNodeArr = this.canvas.data.pens.filter( el => el.data && el.data.nodeType === 'baseNode');
        if ( baseNodeArr.length > 0 ){
          this.baseNode.forEach( el => {
            const curBaseArr = baseNodeArr.filter( e => el.data.data.key === e.data.key );
            if ( curBaseArr.length > 0 ){
              el.noDrag = true;
            }else {
              el.noDrag = false;
            }
          });
        }else {
          toBaseNodeFalse();
        }
        // 工序节点
        const proceesNodeArr = this.canvas.data.pens.filter( el => el.data && el.data.key === 'process');
        if ( proceesNodeArr.length > 0 ){
          this.processData.forEach( el =>{
            const curArr = proceesNodeArr.filter( e => e.data.firstItem.id === el.id);
            if ( curArr.length > 0 ){
              el.noDrag = true;
            }else {
              el.noDrag = false;
            }
          });
        }else {
          toFalse();
        }
      }else {
        toFalse();
        toBaseNodeFalse();
      }
    },
    onMessage(event, node){
      // console.log('onMessage', event, node);
      // 检查禁用工序节点是否可以再次拖拽
      this.checkDrag();
      // 当前节点为工序节点
      const procesNodeCheck = node && node.data && node.data.key === 'process';
      if ( procesNodeCheck && (event === 'node' || event === 'addNode')){
        this.curNode = node;
        this.$store.commit('setCurNode', this.curNode);
        this.selectedRowKeys = node.data.selectedRowKeys;
        this.selectedKeys = node.data.selectedKeys
        this.selectNodeCheck = true;
        // 根据id找到curSelectedNodes
        this.findAndSetCurSelectedNodes(this.selectedRowKeys[0],node.data.configTree);
        // 检查是否有选中的树节点
        this.checkTreeSelect();
      }else if(event === 'redo' || event === 'undo'){
        // 此时 node 为画布数据 撤销 重做时会把里面的div清掉，此时需要重新加上
        node.pens.forEach( el =>{
          if (el && el.data && el.data.key === 'process'){
            el.elementId = this.createDiv(el.data.firstItem);
            el.init();
            this.canvas.render();
          }
        });
        this.selectNodeCheck = false;
      }else{
        switch (event){
          case 'line':
          case 'addLine':
          case 'multi':
          case 'space':
          case 'delete':
          case 'node':
          case 'addNode':
            this.selectNodeCheck = false;
        }
      }
      if (event === 'addNode' && procesNodeCheck){
        node.init();
      }
    },
    getProcesstree(){
      mesPeProcess.getProcesstree({
        definition: ''
      }).then( (res) =>{
        if ( res.code === 0 ){
          let curData = res.data || [];
          curData.forEach(ele =>{
            ele.showName = `${ele.processmcode}(${ele.processmname})`;
            ele.children.forEach(el =>{
              el.showName = `${el.processmcode}(${el.processmname})`;
              el.children.forEach( e =>{
                e.showName = `${e.processmcode}(${e.processmname})`;
              });
            });
          });
          this.allTreeData = curData;
        }
      })
    },
    getAllFirstDef(){
      mesPeProcess.getAllFirstDef({
        keyword: ''
      }).then( (res) =>{
        if ( res.code === 0 ){
          let curData = res.data || [];
          this.processData = curData;
          this.processDataCopy = _.cloneDeep(curData);
          // 此时保证processData有数据调用
          this.checkDrag();
        }
      })
    },
    handleProcessTree(curData){
      let handleData = [];
      curData.forEach( (el, index) =>{
        el.index = index;
        if ( el.children ){
          const length = el.children.length;
          el.children.forEach( (e, i) =>{
            e.index = i;
            e.pIndex = index;
            e.pid = el.id;
            e.childrenLength = length;
          })
        }
      })
      return curData;
    },
    // 获取一级工序下所有的二级工序和工站
    getAllUnderFirstDef(firstProcessCode){
      mesPeProcess.getAllUnderFirstDef({
        firstProcessCode,
      }).then( (res) =>{
        if ( res.code === 0 ){
          console.log(res.data)
          let curData = res.data || [];
          let handleData = [];
          curData.forEach( (el, index) =>{
            handleData.push({
              processmcode: el.processmcode,
              processmname: el.processmname,
              processlayer: el.processlayer,
              id: el.id,
              index: index,
            });
            if ( el.children ){
              const length = el.children.length;
              el.children.forEach( (e, i) =>{
                handleData.push({
                  processmcode: e.processmcode,
                  processmname: e.processmname,
                  processlayer: e.processlayer,
                  childrenLength: length,
                  index: i,
                  id: e.id,
                  pIndex: index,
                  pid: el.id,
                })
              })
            }
          })
          this.modalTableData = handleData;
        }
      })
    },
  },
};
</script>
<style scoped lang='less'>
.drawRoute{
  .draw-con{
    border: 1px solid @c-bg-1; 
  }
  .mainCon{
    display: flex;
  }
  .topBar{
    display: flex;
    height: 40px;
    background: #f3f4f6;
    border-bottom: 1px solid @c-bg-1;
    align-items: center;
  }
  .barItem{
    font-size: 18px;
    margin-left: 10px;
    cursor: pointer;
    color: #737373;
    &:hover{
      color: @c-primary;
    }
  }
  .processItemWrap{
    max-height: 356px;
    overflow-y: auto;
  }
  .dLeft{
    width: 200px;
    border-right: 1px solid @c-bg-1;
    // padding: 10px;
    .inputSearch{
      margin-bottom: 5px;
    }
    .baseNode{
      padding: 4px 0;
      cursor: pointer;
      &:hover{
        color: @c-primary;
      }
    }
    .processNode{
      padding: 4px 0;
      cursor: pointer;
      &:hover{
        color: @c-primary;
      }
    }
    .poros-collapse-borderless{
      background: #fff;
    }
    .poros-collapse-borderless > .poros-collapse-item{
      border-color: @c-bg-1;
      &:last-child{
        border-color: transparent;
      }
    }
  }
  .dMid{
    flex: 1;
    height: 600px;
    border-right: 1px solid @c-bg-1;
    .canvas{
      height: 100%;
    }
  }
  .dRight{
    width: 200px;
    padding: 10px;
    height: 594px;
    overflow: auto;
    /deep/ .poros-tree li .poros-tree-node-content-wrapper{
      overflow: hidden;
      text-overflow: ellipsis;
      width: calc(100% - 24px);
    }
  }
  /deep/ .elementClass{
    pointer-events: auto !important;
    .elementClassChild{
      width: 50px;
      height: 100%;
    }
  }
  .rightBarNoSelect{
    .tipsTitle{
      margin-bottom: 5px;
      color:rgba(0,0,0,0.85);
    }
    >div+div{
      font-size: 13px;
      line-height: 23px;
    }
    span{
      color:rgba(0,0,0,0.85);
    }
  }
  .proceessAtrrPanel{
    margin-top: 20px;
  }
  .noDrag{
    color: rgba(0, 0, 0, 0.25);
    pointer-events: none;
  }
}
.operateBtn{
  margin-left: 6px;
  cursor: pointer;
}
.operateBtn:hover{
  color: @c-primary;
}
/deep/ .processlayer2 > td{
  // background: #dedede !important;
}
/deep/ .processlayer3 > td{
  .poros-table-row-expand-icon{
    visibility: hidden;
  }
}
.tbExra{
  padding-top: 20px;
  border-top: 1px solid #ECEDF0;
  display: flex;
  justify-content: space-around;
  .tClass{
    color: red;
  }
}
</style>